<template>
    <div class="go-chart-configurations-setting">
     <!-- AI聊天对话组件 -->
        <div class="chat-messages" ref="messagesRef">
            <div
                v-for="(message, index) in chatMessages"
                :key="index"
                :class="{ 'self-message': message.role === 'user', 'other-message': message.role === 'assistant' }"
            >
                <component style="width: 20px;height: 20px;" :is="message.role === 'user' ? SunnyIcon : MoonIcon"></component>
                <div class="message-content">{{ message.content }}</div>
            </div>
           <!-- 加载效果 -->
            <div v-if="isLoading" class="loading">
                <span>正在加载回复...</span>
            </div>
        </div>
        <!-- 消息输入框和发送按钮 -->
        <div class="chat-input">
        <input
            v-model="newMessage"
            type="text"
            placeholder="输入消息..."
            @keyup.enter="sendMessage"
        />
        <button :disabled="isLoading" @click="sendMessage">{{ isLoading ? '发送中...' : '发送' }}</button>
        </div>
    </div>
  </template>
  

<script setup lang="ts">
    import { ref, onMounted, watch } from 'vue';
    import { icon } from '@/plugins'
    import { get, post } from '@/api/http'
    const { SunnyIcon, MoonIcon } = icon.ionicons5
    import { useSync } from '@/views/chart/hooks/useSync.hook'

    // BASE_URL
    const LOCAL_BASE_URL = "http://172.20.146.224:8203/coolLowerEngine-api/";
    const BASE_URL = "https://beta-kuda.coocaa.net:9443/violet-api/coolLowerEngine-api/";
    const SESSION_API = "chat/sessions";
    const MESSAGES_API = "chat/sessions/messages";

    const END_BASE_URL = LOCAL_BASE_URL;

    // 聊天消息类型定义
    type ChatMessage = {
        role: 'user' | 'assistant'; // 'user' 表示用户消息，'assistant' 表示助手消息
        content: string;            // content: 消息内容
    }
    const chatMessages = ref<ChatMessage[]>([]);

    // 新消息输入框的值
    const newMessage = ref('');

    // 会话id
    const sessionId = ref('');
    
    // 本次对话是否需要更新看板JSON结构
    const updateBoardJson = ref<number>(2);
    
    // 本次会话是否发送成功
    const sendStatus = ref<number>(1);

    // 对话请求加载状态
    const isLoading = ref<boolean>(false);

    // 聊天消息列表的 DOM 引用
    const messagesRef = ref<HTMLDivElement | null>(null);

    // 更新画板
    const { updateComponent } = useSync()

    // 创建会话
    const createSession = async () => {
        post(
            END_BASE_URL + SESSION_API,
            {
              "functionType": 0,
              "pageUniqueId": "1891160349252517888"
            }
        ).then(res => {
            console.log("createSession res", res)
            sessionId.value = res.data.sessionId;
        }).catch(err => {
            console.log("createSession err", err)
        })
    }

    // 发送消息的函数
    const sendMessage = () => {
        if (sessionId.value === '') {
            console.warn("sessionId is empty")
            return
        }
        if (newMessage.value.trim() !== '') {
            const userMessage: ChatMessage = { role: 'user', content: newMessage.value };
            chatMessages.value.push(userMessage);
            newMessage.value = '';
            isLoading.value = true;
            post(
                END_BASE_URL + MESSAGES_API,
                {
                    "sessionId": sessionId.value,
                    "userPrompt": userMessage.content,
                }
            ).then(async res => {
                console.log("sendMessage res", res)
                chatMessages.value = res.data.chatMessagesList;
                updateBoardJson.value = res.data.updateBoardJson;
                sendStatus.value = res.data.sendStatus;
                if (updateBoardJson.value === 1) {
                  // 可以更新看板
                  // 看板数据
                  const chatMessagesList = res.data.chatMessagesList;
                  const boardData = chatMessagesList[chatMessagesList.length -1];
                  // mock JSON.parse)_ 
                  // {"editCanvasConfig":{"projectName":"A班近周成绩柱状图","width":1920,"height":1080,"filterShow":false,"hueRotate":0,"saturate":1,"contrast":1,"brightness":1,"opacity":1,"rotateZ":0,"rotateX":0,"rotateY":0,"skewX":0,"skewY":0,"blendMode":"normal","background":"rgba(0, 0, 0, 1)","backgroundImage":null,"chartThemeColor":"black","chartCustomThemeColorInfo":null,"chartThemeSetting":{"title":{"show":true,"textStyle":{"color":"#BFBFBF","fontSize":18},"subtextStyle":{"color":"#A2A2A2","fontSize":14}},"xAxis":{"show":true,"nameGap":15,"nameTextStyle":{"color":"#B9B8CE","fontSize":12},"inverse":false,"axisLabel":{"show":true,"fontSize":12,"color":"#B9B8CE","rotate":0},"position":"bottom","axisLine":{"show":true,"lineStyle":{"color":"#B9B8CE","width":1},"onZero":true},"axisTick":{"show":true,"length":5},"splitLine":{"show":false,"lineStyle":{"color":"#484753","width":1,"type":"solid"}}},"yAxis":{"show":true,"nameGap":15,"nameTextStyle":{"color":"#B9B8CE","fontSize":12},"inverse":false,"axisLabel":{"show":true,"fontSize":12,"color":"#B9B8CE","rotate":0},"position":"left","axisLine":{"show":true,"lineStyle":{"color":"#B9B8CE","width":1},"onZero":true},"axisTick":{"show":true,"length":5},"splitLine":{"show":true,"lineStyle":{"color":"#484753","width":1,"type":"solid"}}},"legend":{"show":true,"type":"scroll","x":"center","y":"top","icon":"circle","orient":"horizontal","textStyle":{"color":"#B9B8CE","fontSize":18},"itemWidth":15,"itemHeight":15,"pageTextStyle":{"color":"#B9B8CE"}},"grid":{"show":false,"left":"10%","top":"60","right":"10%","bottom":"60"},"dataset":null,"renderer":"svg","previewScaleType":"fit"}},"requestGlobalConfig":{"requestDataPond":[],"requestOriginUrl":"","requestInterval":30,"requestIntervalUnit":"second","requestParams":{"Body":{"form-data":{},"x-www-form-urlencoded":{},"json":"","xml":""},"Header":{},"Params":{}}},"componentList":[{"id":"id_5o9lbusxntg000","isGroup":false,"attr":{"x":419,"y":167,"w":800,"h":400,"offsetX":0,"offsetY":0,"zIndex":-1},"styles":{"filterShow":false,"hueRotate":0,"saturate":1,"contrast":1,"brightness":1,"opacity":1,"rotateZ":0,"rotateX":0,"rotateY":0,"skewX":0,"skewY":0,"blendMode":"normal","animations":[]},"preview":{"overFlowHidden":false},"status":{"lock":false,"hide":false},"request":{"requestDataType":0,"requestHttpType":"get","requestUrl":"","requestInterval":null,"requestIntervalUnit":"second","requestContentType":0,"requestParamsBodyType":"none","requestSQLContent":{"sql":"select * from  where"},"requestParams":{"Body":{"form-data":{},"x-www-form-urlencoded":{},"json":"","xml":""},"Header":{},"Params":{}}},"filter":null,"events":{"baseEvent":{"click":null,"dblclick":null,"mouseenter":null,"mouseleave":null},"advancedEvents":{"vnodeMounted":null,"vnodeBeforeMount":null},"interactEvents":[]},"key":"BarCommon","chartConfig":{"key":"BarCommon","chartKey":"VBarCommon","conKey":"VCBarCommon","title":"柱状图","category":"Bars","categoryName":"柱状图","package":"Charts","chartFrame":"echarts","image":"bar_x.png"},"option":{"legend":{"show":true,"type":"scroll","x":"center","y":"top","icon":"circle","orient":"horizontal","textStyle":{"color":"#B9B8CE","fontSize":18},"itemHeight":15,"itemWidth":15,"pageTextStyle":{"color":"#B9B8CE"}},"xAxis":{"show":true,"name":"日期","nameGap":15,"nameTextStyle":{"color":"#B9B8CE","fontSize":12},"inverse":false,"axisLabel":{"show":true,"fontSize":12,"color":"#B9B8CE","rotate":0},"position":"bottom","axisLine":{"show":true,"lineStyle":{"color":"#B9B8CE","width":1},"onZero":true},"axisTick":{"show":true,"length":5},"splitLine":{"show":false,"lineStyle":{"color":"#484753","width":1,"type":"solid"}},"type":"category"},"yAxis":{"show":true,"name":"成绩","nameGap":15,"nameTextStyle":{"color":"#B9B8CE","fontSize":12},"inverse":false,"axisLabel":{"show":true,"fontSize":12,"color":"#B9B8CE","rotate":0},"position":"left","axisLine":{"show":true,"lineStyle":{"color":"#B9B8CE","width":1},"onZero":true},"axisTick":{"show":true,"length":5},"splitLine":{"show":true,"lineStyle":{"color":"#484753","width":1,"type":"solid"}},"type":"value"},"grid":{"show":false,"left":"10%","top":"60","right":"10%","bottom":"60"},"tooltip":{"show":true,"trigger":"axis","axisPointer":{"show":true,"type":"shadow"}},"dataset":{"dimensions":["date","score"],"source":[{"date":"周一","score":85},{"date":"周二","score":90},{"date":"周三","score":88},{"date":"周四","score":92},{"date":"周五","score":95},{"date":"周六","score":91},{"date":"周日","score":89}]},"series":[{"type":"bar","barWidth":15,"label":{"show":true,"position":"top","color":"#fff","fontSize":12},"itemStyle":{"color":null,"borderRadius":2}}],"backgroundColor":"rgba(0,0,0,0)"}}]}
                  console.log("boardData", boardData.content)
                  await updateComponent(JSON.parse(boardData.content), true, true)
                  window['$message'].success('看板更新！')
                  // 提交到全局
                }
            }).catch (error => {
                console.error('发送消息失败:', error);
            }).finally(() => {
                isLoading.value = false;
            })
        }
    };

    const testRender = () => {
      const boardData = "{\"editCanvasConfig\":{\"projectName\":\"A班近周成绩柱状图\",\"width\":1920,\"height\":1080,\"filterShow\":false,\"hueRotate\":0,\"saturate\":1,\"contrast\":1,\"brightness\":1,\"opacity\":1,\"rotateZ\":0,\"rotateX\":0,\"rotateY\":0,\"skewX\":0,\"skewY\":0,\"blendMode\":\"normal\",\"background\":\"rgba(0, 0, 0, 1)\",\"backgroundImage\":null,\"chartThemeColor\":\"black\",\"chartCustomThemeColorInfo\":null,\"chartThemeSetting\":{\"title\":{\"show\":true,\"textStyle\":{\"color\":\"#BFBFBF\",\"fontSize\":18},\"subtextStyle\":{\"color\":\"#A2A2A2\",\"fontSize\":14}},\"xAxis\":{\"show\":true,\"nameGap\":15,\"nameTextStyle\":{\"color\":\"#B9B8CE\",\"fontSize\":12},\"inverse\":false,\"axisLabel\":{\"show\":true,\"fontSize\":12,\"color\":\"#B9B8CE\",\"rotate\":0},\"position\":\"bottom\",\"axisLine\":{\"show\":true,\"lineStyle\":{\"color\":\"#B9B8CE\",\"width\":1},\"onZero\":true},\"axisTick\":{\"show\":true,\"length\":5},\"splitLine\":{\"show\":false,\"lineStyle\":{\"color\":\"#484753\",\"width\":1,\"type\":\"solid\"}}},\"yAxis\":{\"show\":true,\"nameGap\":15,\"nameTextStyle\":{\"color\":\"#B9B8CE\",\"fontSize\":12},\"inverse\":false,\"axisLabel\":{\"show\":true,\"fontSize\":12,\"color\":\"#B9B8CE\",\"rotate\":0},\"position\":\"left\",\"axisLine\":{\"show\":true,\"lineStyle\":{\"color\":\"#B9B8CE\",\"width\":1},\"onZero\":true},\"axisTick\":{\"show\":true,\"length\":5},\"splitLine\":{\"show\":true,\"lineStyle\":{\"color\":\"#484753\",\"width\":1,\"type\":\"solid\"}}},\"legend\":{\"show\":true,\"type\":\"scroll\",\"x\":\"center\",\"y\":\"top\",\"icon\":\"circle\",\"orient\":\"horizontal\",\"textStyle\":{\"color\":\"#B9B8CE\",\"fontSize\":18},\"itemWidth\":15,\"itemHeight\":15,\"pageTextStyle\":{\"color\":\"#B9B8CE\"}},\"grid\":{\"show\":false,\"left\":\"10%\",\"top\":\"60\",\"right\":\"10%\",\"bottom\":\"60\"},\"dataset\":null,\"renderer\":\"svg\",\"previewScaleType\":\"fit\"}},\"requestGlobalConfig\":{\"requestDataPond\":[],\"requestOriginUrl\":\"\",\"requestInterval\":30,\"requestIntervalUnit\":\"second\",\"requestParams\":{\"Body\":{\"form-data\":{},\"x-www-form-urlencoded\":{},\"json\":\"\",\"xml\":\"\"},\"Header\":{},\"Params\":{}}},\"componentList\":[{\"id\":\"id_5o9lbusxntg000\",\"isGroup\":false,\"attr\":{\"x\":419,\"y\":167,\"w\":800,\"h\":400,\"offsetX\":0,\"offsetY\":0,\"zIndex\":-1},\"styles\":{\"filterShow\":false,\"hueRotate\":0,\"saturate\":1,\"contrast\":1,\"brightness\":1,\"opacity\":1,\"rotateZ\":0,\"rotateX\":0,\"rotateY\":0,\"skewX\":0,\"skewY\":0,\"blendMode\":\"normal\",\"animations\":[]},\"preview\":{\"overFlowHidden\":false},\"status\":{\"lock\":false,\"hide\":false},\"request\":{\"requestDataType\":0,\"requestHttpType\":\"get\",\"requestUrl\":\"\",\"requestInterval\":null,\"requestIntervalUnit\":\"second\",\"requestContentType\":0,\"requestParamsBodyType\":\"none\",\"requestSQLContent\":{\"sql\":\"select * from  where\"},\"requestParams\":{\"Body\":{\"form-data\":{},\"x-www-form-urlencoded\":{},\"json\":\"\",\"xml\":\"\"},\"Header\":{},\"Params\":{}}},\"filter\":null,\"events\":{\"baseEvent\":{\"click\":null,\"dblclick\":null,\"mouseenter\":null,\"mouseleave\":null},\"advancedEvents\":{\"vnodeMounted\":null,\"vnodeBeforeMount\":null},\"interactEvents\":[]},\"key\":\"BarCommon\",\"chartConfig\":{\"key\":\"BarCommon\",\"chartKey\":\"VBarCommon\",\"conKey\":\"VCBarCommon\",\"title\":\"柱状图\",\"category\":\"Bars\",\"categoryName\":\"柱状图\",\"package\":\"Charts\",\"chartFrame\":\"echarts\",\"image\":\"bar_x.png\"},\"option\":{\"legend\":{\"show\":true,\"type\":\"scroll\",\"x\":\"center\",\"y\":\"top\",\"icon\":\"circle\",\"orient\":\"horizontal\",\"textStyle\":{\"color\":\"#B9B8CE\",\"fontSize\":18},\"itemHeight\":15,\"itemWidth\":15,\"pageTextStyle\":{\"color\":\"#B9B8CE\"}},\"xAxis\":{\"show\":true,\"name\":\"日期\",\"nameGap\":15,\"nameTextStyle\":{\"color\":\"#B9B8CE\",\"fontSize\":12},\"inverse\":false,\"axisLabel\":{\"show\":true,\"fontSize\":12,\"color\":\"#B9B8CE\",\"rotate\":0},\"position\":\"bottom\",\"axisLine\":{\"show\":true,\"lineStyle\":{\"color\":\"#B9B8CE\",\"width\":1},\"onZero\":true},\"axisTick\":{\"show\":true,\"length\":5},\"splitLine\":{\"show\":false,\"lineStyle\":{\"color\":\"#484753\",\"width\":1,\"type\":\"solid\"}},\"type\":\"category\"},\"yAxis\":{\"show\":true,\"name\":\"成绩\",\"nameGap\":15,\"nameTextStyle\":{\"color\":\"#B9B8CE\",\"fontSize\":12},\"inverse\":false,\"axisLabel\":{\"show\":true,\"fontSize\":12,\"color\":\"#B9B8CE\",\"rotate\":0},\"position\":\"left\",\"axisLine\":{\"show\":true,\"lineStyle\":{\"color\":\"#B9B8CE\",\"width\":1},\"onZero\":true},\"axisTick\":{\"show\":true,\"length\":5},\"splitLine\":{\"show\":true,\"lineStyle\":{\"color\":\"#484753\",\"width\":1,\"type\":\"solid\"}},\"type\":\"value\"},\"grid\":{\"show\":false,\"left\":\"10%\",\"top\":\"60\",\"right\":\"10%\",\"bottom\":\"60\"},\"tooltip\":{\"show\":true,\"trigger\":\"axis\",\"axisPointer\":{\"show\":true,\"type\":\"shadow\"}},\"dataset\":{\"dimensions\":[\"date\",\"score\"],\"source\":[{\"date\":\"周一\",\"score\":85},{\"date\":\"周二\",\"score\":90},{\"date\":\"周三\",\"score\":88},{\"date\":\"周四\",\"score\":92},{\"date\":\"周五\",\"score\":95},{\"date\":\"周六\",\"score\":91},{\"date\":\"周日\",\"score\":89}]},\"series\":[{\"type\":\"bar\",\"barWidth\":15,\"label\":{\"show\":true,\"position\":\"top\",\"color\":\"#fff\",\"fontSize\":12},\"itemStyle\":{\"color\":null,\"borderRadius\":2}}],\"backgroundColor\":\"rgba(0,0,0,0)\"}}]}"
        updateComponent(JSON.parse(boardData), true, true)
        window['$message'].success('看板更新！')
    }

    // 滚动到聊天窗口底部的函数
    const scrollToBottom = () => {
        if (messagesRef.value) {
            messagesRef.value.scrollTop = messagesRef.value.scrollHeight;
        }
    };

    // 挂载组件后滚动到底部
    onMounted(() => {
        console.log('AI聊天对话组件')
        createSession()
        scrollToBottom();
        // testRender();
    });

    // 监听聊天消息数组的变化，有新消息时滚动到底部
    watch(chatMessages, () => {
        scrollToBottom();
    });
</script>

<style lang="scss" scoped>
@include go('chart-configurations-setting') {
    display: flex;
    flex-direction: column;
    height: 400px;
    border-radius: 4px;
    overflow: hidden;
    overflow-y: scroll;
}

.chat-messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.self-message,
.other-message {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .avatar-icon {
    width: 20px;
    height: 20px;
  }
  .message-content {
    margin-left: 5px;
  }
}

.self-message {
  justify-content: flex-start;
}

.other-message {
  justify-content: flex-end;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin: 0 10px;
}

.message-content {
  padding: 8px 12px;
  border-radius: 8px;
  max-width: 70%;
}

.self-message .message-content {
  background-color: #007bff;
  color: white;
}

.other-message .message-content {
  background-color: #f0f0f0;
  color: #333;
}

.chat-input {
  display: flex;
  padding: 10px;
  padding-bottom: 0;
  border-top: 1px solid #ccc;
}

.chat-input input {
  flex: 1;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.chat-input button {
  padding: 5px 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.loading {
  text-align: center;
  color: #888;
  margin-top: 10px;
}
</style>
